package com.example.creditscore;

//MyList .java

import java.io.IOException;
import java.sql.Date;
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Credit_score_client_listView extends Activity {
	/** Called when the activity is first created. */
	ListView listView;

	public static String[]clientNumBuilder = new String[] {};
	 
	public static String[]clientNameBuilder = new String[] {};
	
	
	private Timer myTimer;
	
	private EfficientAdapter mListAdapter;
	String currentDateandTime;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_credit_score_client_list);

		
		
	

		

		listView = (ListView) findViewById(R.id.lv_client);
		EfficientAdapter listAdapter = new EfficientAdapter(this);
		listView.setAdapter(listAdapter);
		listView.setOnItemClickListener(listener());
		new LongOperation().execute();
		
	}

	private static class EfficientAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public EfficientAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
		}

		

		public int getCount() {
			return clientNumBuilder.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;

			if (convertView == null) {
				convertView = mInflater.inflate(
						R.layout.activity_credit_score_client_listview, null);
				holder = new ViewHolder();
				holder.text1 = (TextView) convertView
						.findViewById(R.id.TextView01);
				holder.text2 = (TextView) convertView
						.findViewById(R.id.TextView02);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			 

			

			holder.text1.setText(clientNumBuilder[position]);
			holder.text2.setText(clientNameBuilder[position]);
			//System.out.println("client nume builder " + clientNumBuilder[position]);

			return convertView;
		}

		static class ViewHolder {
			TextView text1;
			TextView text2;
		}
		
		
	}

	private OnItemClickListener listener() {
		final Context context = this;
		methods md = new methods();

		return new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				//insert the client id in the list to data
				SharedPreferences preferences = getSharedPreferences("Mb4Me", 0);
				SharedPreferences.Editor editor = preferences.edit();
				//int clientNumInt = Integer.parseInt(clientNumBuilder[position]);
				editor.putString("dClientListNum", clientNumBuilder[position]);
				editor.commit();
				
				Log.d("value ", "result is1  " + clientNumBuilder[position]);
				ProgressDialog dialog = ProgressDialog.show(
						Credit_score_client_listView.this, "",
						"Loading. Please wait...", true);
				showDialog(10);
				
				Intent intent = new Intent(context,
						Credit_score_form_sec_a.class);
				startActivity(intent);
				myTimer.cancel();

			}
		};
	}

	
	public void postDataCheckUpdate() {
		
		int numTimePost = 0;
		// Create a new HttpClient and Post Header
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(
				"http://chandrajcu.webfactional.com/jcumfidatabase/creditscorelist.php");
		HttpPost httppost2 = new HttpPost(
				"http://chandrajcu.webfactional.com/jcumfidatabase/creditscorelistgetIdName.php");
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		if(numTimePost == 0){
		currentDateandTime = sdf.format(0);
		}
		
		
		Log.d("get date time", "date time " + currentDateandTime);
		
		try {

			// Add your data
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
			nameValuePairs.add(new BasicNameValuePair("timeStamp",
					currentDateandTime));

			// Execute HTTP Post Request
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String response = httpclient.execute(httppost, responseHandler);
			String[] splits = response.split("/");
			Log.d("server response", "response " + splits[0] + " " + splits[1]);
			
				if(splits[0].equals("newUpdate")){
					ArrayList<String>  clientNumList= new ArrayList<String>();
					ArrayList<String>  clientNameList= new ArrayList<String>();
					String responseIDnName = httpclient.execute(httppost2, responseHandler);
					int x = 0;
					
					int y = 1;
					responseIDnName.split(":");
					
					//ArrayList<String> receiveServerInfo = new ArrayList<String>();
					
					String[] splits2 = responseIDnName.split(":");
					Log.d("split length", "split length " + splits.length);
					for(int i = 0; i<splits2.length;i = i+2){
						
						clientNumList.add(splits2[x]);
						
						clientNameList.add(splits2[y]);
						
						x = x+2;
						y = y+2;
						numTimePost++;
						
						
					
						/*Log.d("client name" , "client name" + splits[x]);
						Log.d("client name" , "client name2" + splits[y]);
						Log.d("client name" , "client name" + splits[x]);
						Log.d("client name" , "client name2" + splits[y]);*/
					}
					
					//Set the timestamp on the lastest entry
					if(numTimePost > 0){
						currentDateandTime = splits[1];
						Log.d("current date and time","Current date and time" + currentDateandTime );
						}
					
					clientNumBuilder = clientNumList.toArray(clientNumBuilder);
					clientNameBuilder = clientNameList.toArray(clientNameBuilder);
					Log.d("client name3" , "client name3");
					
					this.runOnUiThread(new Runnable() {
					    public void run() {
					    	((BaseAdapter) listView.getAdapter()).notifyDataSetChanged();
					    }
					});
					
					
				
			}
			
		

		} catch (ClientProtocolException e) {

			Log.d("error", "error3 " + e);
			// TODO Auto-generated catch block
		} catch (IOException e) {
			Log.d("error", "error2 " + e);
			System.out.println("IOE response" + e.toString());
			// TODO Auto-generated catch block
		} catch (ArrayIndexOutOfBoundsException e) {
			Log.d("error", "error 3" + e);
		}

	}// end postData()

	private class LongOperation extends AsyncTask<Void, Integer, String> {
		@Override
		protected String doInBackground(Void... params) {
			myTimer = new Timer();
			myTimer.schedule(new TimerTask() {
				@Override
				public void run() {

					postDataCheckUpdate();
					
				}
			}, 0, 10000);
			return null;

		}
		
	
	}
}
